﻿using System;

namespace Ooaavee.Scripting
{
    /// <summary>
    /// Makes a code block to use a user specified programming language as a default programming language in scripts.
    /// </summary>
    public sealed class LanguageScope : IDisposable
    {
        private Language PreviousLanguage { set; get; }
        private bool IsDisposed { set; get; }

        /// <summary>
        /// No public constructor available, use Get method.
        /// </summary>
        private LanguageScope() { }

        /// <summary>
        /// Gets a new instance of LanguageScope class.
        /// </summary>
        /// <param name="scopeLanguage">A programming language.</param>
        /// <returns>LanguageScope</returns>
        public static LanguageScope Get(Language scopeLanguage)
        {
            LanguageScope scope = new LanguageScope
                                      {
                                          PreviousLanguage = ScriptingContext.Default.Language
                                      };

            ScriptingContext.Default.Language = scopeLanguage;

            return scope;
        }

        void IDisposable.Dispose()
        {
            if (IsDisposed)
            {
                throw new ObjectDisposedException("this");
            }

            try
            {
                ScriptingContext.Default.Language = PreviousLanguage;
            }
            finally
            {
                IsDisposed = true;
            }
        }
    }
}
